/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: EmployeeController
 * Author:   zhouheng
 * Date:     2018/5/21 10:57
 * Description: emp控制层
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.hengby.hengcrud.modular.sys.controller;

import com.hengby.hengcrud.modular.sys.mapper.UserMapper;
import com.hengby.hengcrud.modular.sys.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 〈一句话功能简述〉<br> 
 * 〈emp控制层〉
 *
 * @author zhouheng
 * @create 2018/5/21
 * @since 1.0.0
 */
@RestController
@CacheConfig(cacheNames = "emp",keyGenerator = "myKeyGenerator")
public class CacheController {
    @Autowired
    UserMapper userMapper;

    /*
    cachemanager 管理多个cache组件    cachenName 缓存名字
     */
    @GetMapping("emp/{id}")
    @Cacheable(cacheNames = "emp",keyGenerator = "myKeyGenerator",condition = "#a0 > 1")
    public User getEmp(@PathVariable("id") Integer id){
        return null;
    }

    /**
     * 即先调用方法 又更新缓存
     * @param user
     * @return
     */
    @CachePut(value = "emp", key = "#result.id")
    @GetMapping("emp")
    public User updateEmp(User user){
        userMapper.save(user);

        return  user;
    }

    @GetMapping("delemp/{id}")
    @CacheEvict(value = "emp",allEntries = true,beforeInvocation = false)
    public void deleteEmp(@PathVariable("id") Integer id){
        System.out.println("employee:"+id);

    }

    @Caching(
            cacheable = {
                  @Cacheable(value = "emp",keyGenerator = "#lastName")
            },
            put = {
                @CachePut(value = "emp", key = "#result.id")
            },
            evict = {

            }
    )
    @GetMapping("emp/lastname/{lastName}")
    public User getEmployeeByLastName(@PathVariable("lastName") String lastName){
        List<User> userList = userMapper.findByLastName(lastName);

        System.out.println(userList.get(0).toString());

        return  userList.get(0);
    }
}